<template>
  <a-drawer
    :title="title + $t('message.User')"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: 100%"
  >
    <template slot="title">
      <div style="width: 100%">
        <span>{{ title }}</span>
        <span
          style="
            display: inline-block;
            width: calc(100% - 51px);
            padding-right: 10px;
            text-align: right;
          "
        >
          <a-button
            @click="toggleScreen"
            icon="appstore"
            style="height: 20px; width: 20px; border: 0px"
          ></a-button>
        </span>
      </div>
    </template>

    <a-spin :spinning="confirmLoading">
      <div style="margin: 0 16px">
        <a-form-model
          ref="form"
          :model="model"
          :rules="validatorRules"
          labelAlign="left"
        >
          <a-form-model-item
            :label="$t('message.User_name')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="realname"
          >
            <a-input
              :placeholder="$t('message.Please_enter_the_user_name')"
              v-model="model.realname"
            />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('message.User_Accounts')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="username"
          >
            <a-input
              :placeholder="$t('message.Please_enter_the_user_account')"
              v-model="model.username"
              :disabled="model.id"
            />
          </a-form-model-item>
          <template v-if="!model.id">
            <a-form-model-item
              :label="$t('message.Login_password')"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="password"
            >
              <a-input
                type="password"
                :placeholder="$t('message.Please_enter_password')"
                v-model="model.password"
              />
            </a-form-model-item>
            <a-form-model-item
              :label="$t('message.Confirm_password')"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="confirmpassword"
            >
              <a-input
                type="password"
                @blur="handleConfirmBlur"
                :placeholder="$t('message.Please_enter')"
                v-model="model.confirmpassword"
              />
            </a-form-model-item>
          </template>
          <a-form-model-item
            :label="$t('message.phone')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="phone"
          >
            <a-input
              :placeholder="$t('message.Please_enter_phone')"
              v-model="model.phone"
            />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('message.email')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="email"
          >
            <a-input
              :placeholder="$t('message.Please_enter_email')"
              v-model="model.email"
            />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('message.Organizational_choice')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="departId"
          >
            <a-tree-select
              v-model="model.departId"
              style="width: 100%"
              :placeholder="$t('message.Please_select_the_organization')"
              show-search
              treeNodeFilterProp="title"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="treeData"
              tree-default-expand-all
            >
            </a-tree-select>
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-spin>

    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-popconfirm
        :title="$t('message.Are_you_sure_to_give_up_editing') + '？'"
        @confirm="handleCancel"
        :okText="$t('message.Confirm')"
        :cancelText="$t('message.Cancel')"
      >
        <a-button style="margin-right: 0.8rem">{{
          $t("message.Cancel")
        }}</a-button>
      </a-popconfirm>
      <a-button
        @click="handleSubmit"
        type="primary"
        :loading="confirmLoading"
        >{{ $t("message.Confirm") }}</a-button
      >
    </div>
  </a-drawer>
</template>

<script>
import moment from "moment";
import Vue from "vue";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { getAction, postAction } from "@/api/manage";
import { queryUserRole, duplicateCheck } from "@/api/api";

export default {
  name: "UserModal",
  components: {},
  data() {
    return {
      departDisabled: false, //是否是我的部门调用该页面
      roleDisabled: false, //是否是角色维护调用该页面
      showSystemUser: true,
      modalWidth: 800,
      drawerWidth: 700,
      modaltoggleFlag: true,
      confirmDirty: false,
      userId: "", //保存用户id
      disableSubmit: false,
      dateFormat: "YYYY-MM-DD",
      validatorRules: {
        username: [
          { required: true, message: "请输入用户账号!" },
          { validator: this.validateUsername },
        ],
        password: [
          {
            required: true,
            pattern:
              /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
            message: "密码由8位数字、大小写字母和特殊符号组成!",
          },
          { validator: this.validateToNextPassword, trigger: "change" },
        ],
        confirmpassword: [
          { required: true, message: "请重新输入登录密码!" },
          { validator: this.compareToFirstPassword },
        ],
        realname: [{ required: true, message: "请输入用户名称!" }],
        phone: [
          { required: true, message: "请输入手机号!" },
          { validator: this.validatePhone },
        ],
        email: [{ validator: this.validateEmail }],
        workNo: [
          { required: true, message: "请输入工号" },
          { validator: this.validateWorkNo },
        ],
        telephone: [
          {
            pattern: /^0\d{2,3}-[1-9]\d{6,7}$/,
            message: "请输入正确的座机号码",
          },
        ],
        departId: [{ required: true, message: "请选择部门" }],
      },
      departIdShow: false,
      title: "操作",
      visible: false,
      model: {},
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
      uploadLoading: false,
      confirmLoading: false,
      headers: {},
      treeData: [],
      url: {
        fileUpload: window._CONFIG["domianURL"] + "/sys/common/upload",
        userWithDepart: "/sys/user/userDepartList", // 引入为指定用户查看部门信息需要的url
        userId: "/sys/user/generateUserId", // 引入生成添加用户情况下的url
        treeData: "/orgDept/getTree",
        save: "/orgUser/save",
      },
      tenantsOptions: [],
      rolesOptions: [],
      nextDepartOptions: [],
    };
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN);
    this.headers = { "X-Access-Token": token };
    this.getTreeData();
  },
  computed: {
    uploadAction: function () {
      return this.url.fileUpload;
    },
  },
  methods: {
    add() {
      this.visible = true;
      this.showSystemUser = false;
      this.refresh();
      this.edit({ activitiSync: "0", userIdentity: 1 });
    },
    edit(record) {
      let that = this;
      that.visible = true;
      //根据屏幕宽度自适应抽屉宽度
      this.resetScreenSize();
      that.userId = record.id;
      that.model = Object.assign(
        {},
        { selectedroles: "", selecteddeparts: "" },
        record
      );
      //身份为上级显示负责部门，否则不显示
      if (this.model.userIdentity == 2) {
        this.departIdShow = true;
      } else {
        this.departIdShow = false;
      }

      if (record.hasOwnProperty("id")) {
        that.getUserRoles(record.id);
        that.getUserDeparts(record.id);
      }
      console.log("that.model=", that.model);
    },
    //窗口最大化切换
    toggleScreen() {
      if (this.modaltoggleFlag) {
        this.modalWidth = window.innerWidth;
      } else {
        this.modalWidth = 800;
      }
      this.modaltoggleFlag = !this.modaltoggleFlag;
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth;
      } else {
        this.drawerWidth = 700;
      }
    },
    getUserRoles(userid) {
      queryUserRole({ userid: userid }).then((res) => {
        if (res.success) {
          this.model.selectedroles = res.result.join(",");
          console.log("that.model.selectedroles=", this.model.selectedroles);
        }
      });
    },
    getUserDeparts(userid) {
      let that = this;
      getAction(that.url.userWithDepart, { userId: userid }).then((res) => {
        if (res.success) {
          let departOptions = [];
          let selectDepartKeys = [];
          for (let i = 0; i < res.result.length; i++) {
            selectDepartKeys.push(res.result[i].key);
            //新增负责部门选择下拉框
            departOptions.push({
              value: res.result[i].key,
              label: res.result[i].title,
            });
          }
          that.model.selecteddeparts = selectDepartKeys.join(",");
          that.nextDepartOptions = departOptions;
          console.log("that.nextDepartOptions=", that.nextDepartOptions);
        }
      });
    },
    backDepartInfo(info) {
      this.model.departIds = this.model.selecteddeparts;
      this.nextDepartOptions = info.map((item, index, arr) => {
        let c = { label: item.text, value: item.value + "" };
        return c;
      });
    },
    refresh() {
      this.userId = "";
      this.nextDepartOptions = [];
      this.departIdShow = false;
    },
    close() {
      this.$emit("close");
      this.visible = false;
      this.disableSubmit = false;
      this.nextDepartOptions = [];
      this.departIdShow = false;
      this.$refs.form.resetFields();
    },
    moment,
    handleSubmit() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true;
          //如果是上级择传入departIds,否则为空
          if (this.model.userIdentity !== 2) {
            this.model.departIds = "";
          }
          let obj;
          postAction(this.url.save, this.model)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit("ok");
              } else {
                that.$message.warning(res.message);
              }
            })
            .finally(() => {
              that.confirmLoading = false;
              that.close();
            });
        }
      });
    },
    handleCancel() {
      this.close();
    },
    validateToNextPassword(rule, value, callback) {
      const confirmpassword = this.model.confirmpassword;
      if (value && confirmpassword && value !== confirmpassword) {
        callback(
          this.$t("message.The_passwords_entered_twice_are_different") + "！"
        );
      }
      if (value && this.confirmDirty) {
        this.$refs.form.validateField(["confirmpassword"]);
      }
      callback();
    },
    compareToFirstPassword(rule, value, callback) {
      if (value && value !== this.model.password) {
        callback(
          this.$t("message.The_passwords_entered_twice_are_different") + "！"
        );
      } else {
        callback();
      }
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback();
      } else {
        if (new RegExp(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/).test(value)) {
          var params = {
            tableName: "sys_user",
            fieldName: "phone",
            fieldVal: value,
            dataId: this.userId,
          };
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback();
            } else {
              callback(
                this.$t("message.The_mobile_phone_number_already_exists") + "!"
              );
            }
          });
        } else {
          callback(
            this.$t(
              "message.Please_enter_the_mobile_phone_number_in_the_correct_format"
            ) + "!"
          );
        }
      }
    },
    validateEmail(rule, value, callback) {
      if (!value) {
        callback();
      } else {
        if (
          new RegExp(
            /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
          ).test(value)
        ) {
          var params = {
            tableName: "sys_user",
            fieldName: "email",
            fieldVal: value,
            dataId: this.userId,
          };
          duplicateCheck(params).then((res) => {
            console.log(res);
            if (res.success) {
              callback();
            } else {
              callback(
                this.$t("message.The_email_address_already_exists") + "!"
              );
            }
          });
        } else {
          callback(
            this.$t(
              "message.Please_enter_the_email_address_in_the_correct_format"
            ) + "!"
          );
        }
      }
    },
    validateUsername(rule, value, callback) {
      var params = {
        tableName: "sys_user",
        fieldName: "username",
        fieldVal: value,
        dataId: this.userId,
      };
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback();
        } else {
          callback(this.$t("message.The_username_already_exists") + "!");
        }
      });
    },
    validateWorkNo(rule, value, callback) {
      var params = {
        tableName: "sys_user",
        fieldName: "work_no",
        fieldVal: value,
        dataId: this.userId,
      };
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback();
        } else {
          callback(this.$t("message.The_employee_number_already_exists") + "!");
        }
      });
    },
    handleConfirmBlur(e) {
      const value = e.target.value;
      this.confirmDirty = this.confirmDirty || !!value;
    },
    beforeUpload: function (file) {
      var fileType = file.type;
      if (fileType.indexOf("image") < 0) {
        this.$message.warning(this.$t("message.Please_upload_pictures"));
        return false;
      }
      //TODO 验证文件大小
    },
    identityChange(e) {
      if (e.target.value === 1) {
        this.departIdShow = false;
      } else {
        this.departIdShow = true;
      }
    },
    getTreeData() {
      getAction(this.url.treeData, {}).then((res) => {
        if (res.success) {
          this.treeData = res.result;
        }
      });
    },
  },
};
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 104px;
  height: 104px;
}

.ant-upload-select-picture-card i {
  font-size: 49px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

.drawer-bootom-button {
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}

/*【JTC-502】 添加用户两个滚动条*/
/deep/ .ant-drawer-body {
  padding-bottom: 53px;
}
</style>
